#include "common_regex.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> 
#include "common_log.h"

#pragma comment(lib, "regex")

int Regex_Run(const char *regex, const char *string, int flags, int nmatch, 
			int (*DoRegexMatch)(const char *string, int start, int end)) {
	regmatch_t *regmt = NULL;
	regex_t regt;
	char err[128];
	int index, ret;
	int result = -1;
	
	ret = regcomp(&regt, regex, flags);
	if (0 != ret) {
		regerror(ret, &regt, err, sizeof(err));
		LOGERROR("regcomp(%s,%d)={%d,%s}\n", regex, flags, ret, err);
	}
	else {
		regmt = (regmatch_t *)malloc(sizeof(regmatch_t) * nmatch);
		ret = regexec(&regt, string, nmatch, regmt, 0);
		if (0 != ret) {
			regerror(ret, &regt, err, sizeof(err));
			LOGERROR("regexec(%s,%s,%d)={%d,%s}\n", regex, string, nmatch, ret, err);		
		}
		else {
			for (index = 0; index < nmatch; index++) {
				if (-1 == regmt[index].rm_so || -1 == regmt[index].rm_eo) 
					break;		
				if (NULL == DoRegexMatch)
					result = 0;
				else
					result = DoRegexMatch(string, regmt[index].rm_so, regmt[index].rm_eo);
			}
		}
		free(regmt);
	}
	regfree(&regt);	
	
	return result;
}

int Regex_Run2(const char *regex, const char *str, const char *regex2, const char *str2, int flags, int nmatch, void *remaindata, 
			   int (*DoRegexMatch)(const char *str, int start, int end, const char *str2, int start2, int end2, void *remaindata)) {
	regmatch_t *regmt = NULL, *regmt2 = NULL;
	regex_t regt, regt2;
	char err[128];
	int index, ret, ret2;
	int result = -1;
	
	ret = regcomp(&regt, regex, flags);
	ret2 = regcomp(&regt2, regex2, flags);
	if (0 != ret || 0 != ret2) {
		regerror(ret, &regt, err, sizeof(err));
		LOGERROR("regcomp(%s,%d)={%d,%s}\n", regex, flags, ret, err);
		regerror(ret2, &regt2, err, sizeof(err));
		LOGERROR("regcomp(%s,%d)={%d,%s}\n", regex2, flags, ret2, err);
	}
	else {
		regmt = (regmatch_t *)malloc(sizeof(regmatch_t) * nmatch);
		regmt2 = (regmatch_t *)malloc(sizeof(regmatch_t) * nmatch);
		ret = regexec(&regt, str, nmatch, regmt, 0);
		ret2 = regexec(&regt2, str2, nmatch, regmt2, 0);
		if (0 != ret || 0 != ret2) {
			regerror(ret, &regt, err, sizeof(err));
			LOGERROR("regexec(%s,%s,%d)={%d,%s}\n", regex, str, nmatch, ret, err);		
			regerror(ret2, &regt2, err, sizeof(err));
			LOGERROR("regexec(%s,%s,%d)={%d,%s}\n", regex2, str2, nmatch, ret2, err);	
		}
		else {
			for (index = 0; index < nmatch; index++) {
				if (-1 == regmt[index].rm_so || -1 == regmt[index].rm_eo 
					|| -1 == regmt2[index].rm_so || -1 == regmt2[index].rm_eo) 
					break;		
				if (NULL == DoRegexMatch)
					result = 0;
				else
					result = DoRegexMatch(str, regmt[index].rm_so, regmt[index].rm_eo, 
						str2, regmt2[index].rm_so, regmt2[index].rm_eo, remaindata);
			}
		}
		free(regmt);
		free(regmt2);
	}
	regfree(&regt);	
	regfree(&regt2);
	
	return result;
}



